package com.airpi.listeners;

import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;

/**
 * Class which permits to listen a click on a {@link Drawable} in an {@link EditText}
 */
public abstract class RightDrawableOnTouchListener implements OnTouchListener {

	Drawable drawable;
    private int fuzz = 10;

    /**
     * Creates a new {@link RightDrawableOnTouchListener}, which will permit to listen an {@link EditText}'s {@link Drawable}
     * @param edittext The {@link EditText} which contains a {@link Drawable} it has to be clickable
     */
    public RightDrawableOnTouchListener(EditText edittext) {
        super();
        final Drawable[] drawables = edittext.getCompoundDrawables();
        if (drawables != null && drawables.length == 4)
            this.drawable = drawables[2];
    }

    /**
     * Indicates in the {@link EditText} where is the clickable {@link Drawable}
     * @param edittext The {@link EditText} which contains a {@link Drawable} it has to be clickable
     * @param event The {@link MotionEvent} corresponding to a click
     */
    @Override
    public boolean onTouch(final View v, final MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && drawable != null) {
            final int x = (int) event.getX();
            final int y = (int) event.getY();
            final Rect bounds = drawable.getBounds();
            if (x >= (v.getRight() - bounds.width() - fuzz) && x <= (v.getRight() - v.getPaddingRight() + fuzz)
                    && y >= (v.getPaddingTop() - fuzz) && y <= (v.getHeight() - v.getPaddingBottom()) + fuzz) {
                return onDrawableTouch(event);
            }
        }
        return false;
    }

    /**
     * The action to do when the {@link Drawable} is clicked
     * @param event The {@link MotionEvent} corresponding to a click
     * @return false
     */
    public abstract boolean onDrawableTouch(final MotionEvent event);

}
